<template>
  <div
    ref="editFieldRef"
    class="edit-field__wrapper"
    :class="mouseOver ? 'edit-field-mouse_wrapper' : ''">
    <text-ell
      v-bind="$attrs"
      :class="[contentClass, 'cursor-pointer']"
      @click="handleClick">
      <slot>
        <slot v-if="contentType === 'text'">{{ content || '-' }} </slot>
        <span v-else> {{ formatUnix(content) || '-' }}</span>
      </slot>
    </text-ell>
    <i-icons-edit
      v-show="content || content !== '-'"
      class="edit-icon !flex-shrink-0"
      :class="hoverTable ? 'hover-visible__tr' : ''"
      @click="handleEdit" />
  </div>

  <cloud-dialog
    v-model:visible="visible"
    :title="editTitle"
    :width="480"
    :loading="loading"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-open="handleBeforeOpen">
    <a-form
      ref="formRef"
      :model="formData"
      :rules="noVerification ? {} : formRules"
      layout="vertical">
      <a-form-item
        class="mb-0!"
        field="name"
        :label="label"
        asterisk-position="end"
        :hide-asterisk="hideAsterisk"
        :required="required">
        <a-input
          v-if="type === 'input'"
          v-model="formData.name"
          :max-length="maxLength"
          show-word-limit
          :placeholder="placeholder">
        </a-input>
        <a-select
          v-if="type === 'select'"
          v-model="formData.name"
          :options="options" />
        <a-date-picker
          v-if="type === 'date'"
          v-model="formData.name"
          show-time
          format="YYYY-MM-DD"
          value-format="X"
          class="w-full" />
        <a-textarea
          v-if="type === 'textarea'"
          v-model="formData.name"
          :max-length="maxLength"
          show-word-limit
          :auto-size="{ maxRows: 3, minRows: 3 }" />
      </a-form-item>
    </a-form>
  </cloud-dialog>
</template>

<script setup lang="ts">
import type { PromiseFn } from '@/apis/schema/all'
import usePopup from '@/hooks/usePopup'
import { type FieldRule, type FormInstance } from '@arco-design/web-vue'
import CloudDialog from './CloudDialog.vue'

import type { LabelValue } from '@arco-design/web-vue/es/tree-select/interface'
import type { TextEllProps } from './TextEll.vue'
const { visible, open } = usePopup()
export interface EditFieldProps extends TextEllProps {
  type: 'input' | 'select' | 'textarea' | 'date'
  mouseOver?: boolean
  successMessage?: string
  hoverTable?: boolean
  editTitle?: string
  maxLength?: number
  contentClass?: string
  contentType?: 'text' | 'date'
  placeholder?: string
  ruleMessage?: string
  noVerification?: boolean
  fn?: PromiseFn
  refreshFn?: PromiseFn
  field?: string
  href?: string
  defaultValue?: string
  required?: boolean
  options?: LabelValue[] | any
  fieldNames?: LabelValue
  label?: string
  hideAsterisk?: boolean
  validator?: FieldRule<string>['validator']
  params?: {
    [x: string]: any
  }
}
const props = withDefaults(defineProps<EditFieldProps>(), {
  mouseOver: false,
  hoverTable: false,
  noVerification: false,
  field: 'name',
  editTitle: '重命名',
  placeholder: '请输入',
  ruleMessage: '不能为空',
  label: '名称',
  contentType: 'text',
  required: true,
  hideAsterisk: false
})

const formRef = ref<FormInstance>()
const formData = reactive({
  name: ''
})
const loading = ref(false)
const formRules = computed(() => {
  const rules: FieldRule[] = [
    {
      required: props.required,
      validator(value, callback) {
        if (!value) {
          callback(props.ruleMessage)
          return
        }
        callback()
      }
    }
  ]
  // if (props.validator) {
  //   rules.push({ validator: props.validator })
  // }
  return { name: rules }
})

const editFieldRef = ref<HTMLElement>()
const handleEdit = () => {
  formRef.value?.resetFields()
  formData.name = props.defaultValue || ''
  open()
}
const router = useRouter()

const handleClick = () => {
  if (props?.href) {
    router.push(props.href)
  }
}

async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error) {
    return false
  }
  loading.value = true
  // 提交表单
  return await props
    ?.fn?.({
      ...(props?.params || {}),
      [props.field]:
        props.type === 'date' ? Number(formData.name) : formData.name
    })
    .then(async () => {
      ToastUtils.success(props.successMessage ?? '操作成功')
      await props?.refreshFn?.()
      return Promise.resolve(true)
    })
    .catch(() => Promise.reject(false))
    .finally(() => {
      loading.value = false
    })
}
const handleBeforeOpen = async () => {
  formData.name = props?.defaultValue || ''
  //修改options中的键为 value label
  // if (props?.fieldNames) {
  //   customOptions.value = props.options?.map((item: LabelValue | any) => {
  //     return {
  //       value: item[props.fieldNames!.value!],
  //       label: item[props.fieldNames!.label!]
  //     }
  //   })
  // }
}
</script>

<style lang="less" scoped>
@edit-size: 16px;
.edit-field__wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  :deep(.text-ell) {
    flex: initial;
    width: max-content;
  }
}
.edit-icon {
  width: @edit-size;
  height: @edit-size;
  color: #bfc2c7;
  cursor: pointer;
  transition: color 0.2s;
  flex-shrink: 0;
  &:hover {
    color: var(--color-text-2) !important;
  }
  svg {
    width: @edit-size;
    height: @edit-size;
  }
}

.arco-table-tr {
  .edit-icon {
    opacity: 0;
    display: none;
  }
  &:hover {
    .edit-icon {
      opacity: 1;
      display: inline-block;
    }
  }
}

.edit-field-mouse_wrapper {
  .edit-icon {
    @apply hidden;
  }
  &:hover {
    .edit-icon {
      @apply inline-block;
    }
  }
}
</style>
